package com.mky.mkcompany.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mky.mkcompany.controller.domain.*;
import com.mky.mkcompany.dao.*;
import com.mky.mkcompany.dic.UserStatusDic;
import com.mky.mkcompany.exception.WafException;
import com.mky.mkcompany.model.*;
import com.mky.mkcompany.tool.DateUtil;
import com.mky.mkcompany.tool.PasswordUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.persistence.EntityManager;
import java.util.*;

/**
 * Created by Lenovo on 2017/9/1.
 */
@Service
public class UserManageService {
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());
    @Autowired
    private QuestTypeDao questTypeDao;
    @Autowired
    private TestInfoDao testInfoDao;
    @Autowired
    private SubjectChapterDao subjectChapterDao;
    @Autowired
    private SubjectCategoryDao subjectCategoryDao;

    @Autowired
    private EntityManager em;

    @Autowired
    private TestQuestDao testQuestDao;
    @Autowired
    private PracticQuestDao practicQuestDao;
    @Autowired
    private CourseQuestDao courseQuestDao;
    @Autowired
    private CourseInfoDao courseInfoDao;
    @Autowired
    private CourseCategoryDao courseCategoryDao;
    @Autowired
    private CourseSubjectDao courseSubjectDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserExamTypeDao userExamTypeDao;
    @Autowired
    private MessageReleaseDao messageReleaseDao;
    @Autowired
    private AdminUserDao adminUserDao;

    @Autowired
    private UserDoPracticQuestDao userDoPracticQuestDao;
    @Autowired
    private UserCollectPracticQuestDao userCollectPracticQuestDao;
    @Autowired
    private UserTestDao userTestDao;
    @Autowired
    private UserDoTestDao userDoTestDao;
    @Autowired
    private UserDoTestQuestDao userDoTestQuestDao;
    @Autowired
    private UserDoTestSaveQuestDao userDoTestSaveQuestDao;
    @Autowired
    private UserCourseDao userCourseDao;
    @Autowired
    private UserDoCourseDao userDoCourseDao;
    @Autowired
    private UserDoCourseQuestDao userDoCourseQuestDao;
    @Autowired
    private UserDoCourseSaveQuestDao userDoCourseSaveQuestDao;




    public JSONObject getUserList(String mobile,int page,int size){
        JSONObject res = new JSONObject();
        Sort sort=new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = new PageRequest(page-1, size, sort);
        Page<User> userPage=null;
        if("all".equals(mobile)){
            userPage=userDao.findAll(pageable);
        }else {
            userPage=userDao.findByMobileLike(mobile,pageable);
        }
        List<AdminUser> adminUsers=adminUserDao.findAll();
        res.put("data",userPage.getContent());
        JSONArray users=res.getJSONArray("data");
        res.put("data",adminUsers);
        JSONArray admins=res.getJSONArray("data");
        users.addAll(admins);
        res.put("data",users);
        res.put("total",userPage.getTotalElements()+adminUsers.size());
        return res;
    }

    public JSONObject saveUser(User userReq){
        JSONObject res = new JSONObject();
        String type=userReq.getType();
        if(type.equals("ordinary")) {
            //普通用户，用于客户使用
            User userOld = userDao.findByUsername(userReq.getUsername());
            if (userOld != null) {
                throw new WafException("", "用户名重复！", HttpStatus.NOT_ACCEPTABLE);
            } else {
                User user = new User();
                user.setId(UUID.randomUUID().toString().replace("-", ""));
                user.setUsername(userReq.getUsername());
                String salt = "123456";
                String password = userReq.getPassword();
                String passwd = PasswordUtil.encryptPassword(password, salt);
                user.setPassword(passwd);
                user.setType(userReq.getType());
                user.setMobile(userReq.getMobile());
                user.setDelStatus(0);
                user.setValid(UserStatusDic.ENABLE);
                user.setSalt(salt);
                user.setCreateTime(DateUtil.getNowTimestamp());
                user.setUpdateTime(DateUtil.getNowTimestamp());
                userDao.save(user);
            }
        }else{
            //管理员用户，用于后台的管理
            AdminUser userOld = adminUserDao.findByUsername(userReq.getUsername());
            if (userOld != null) {
                throw new WafException("", "用户名重复！", HttpStatus.NOT_ACCEPTABLE);
            } else {
                AdminUser user = new AdminUser();
                user.setId(UUID.randomUUID().toString().replace("-", ""));
                user.setUsername(userReq.getUsername());
                String salt = "123456";
                String password = userReq.getPassword();
                String passwd = PasswordUtil.encryptPassword(password, salt);
                user.setPassword(passwd);
                user.setType(userReq.getType());
                user.setValid(UserStatusDic.ENABLE);
                user.setSalt(salt);
                user.setCreateTime(DateUtil.getNowTimestamp());
                user.setUpdateTime(DateUtil.getNowTimestamp());
                adminUserDao.save(user);
            }
        }
        return res;
    }

    public void delUser(String id,String type){
        if(type.equals("ordinary")) {
            userDao.deleteById(id);
            userDoPracticQuestDao.deleteByUserId(id);
            userCollectPracticQuestDao.deleteByUserId(id);
            userTestDao.deleteByUserId(id);
            userDoTestDao.deleteByUserId(id);
            userDoTestQuestDao.deleteByUserId(id);
            userDoTestSaveQuestDao.deleteByUserId(id);
            userCourseDao.deleteByUserId(id);
            userDoCourseDao.deleteByUserId(id);
            userDoCourseQuestDao.deleteByUserId(id);
            userDoCourseSaveQuestDao.deleteByUserId(id);
        }else{
            adminUserDao.deleteById(id);
        }
    }

    public JSONObject updatePassword(String type,String userId,String newPassword){
        JSONObject res = new JSONObject();
        String salt="a123456";
        if(type.equals("admin")){ //管理员
            AdminUser user = adminUserDao.findOne(userId);
            String newPasswd = PasswordUtil.encryptPassword(newPassword, salt);
            user.setPassword(newPasswd);
            user.setSalt(salt);
            user.setUpdateTime(DateUtil.getNowTimestamp());
            adminUserDao.save(user);
        }else {
            User userOld = userDao.findById(userId);
            String newPasswd = PasswordUtil.encryptPassword(newPassword, salt);
            userOld.setPassword(newPasswd);
            userOld.setSalt(salt);
            userOld.setUpdateTime(DateUtil.getNowTimestamp());
            userDao.save(userOld);
        }
        return res;
    }

    public JSONObject resetPassword(String password,String userId){
        JSONObject res = new JSONObject();
        User userOld=userDao.findById(userId);
        if(userOld==null){
            AdminUser adminUser=adminUserDao.findOne(userId);
            if(adminUser==null){
                throw new WafException("", "用户不存在！", HttpStatus.NOT_ACCEPTABLE);
            }else{
                String salt="a123456";
                String passwd= PasswordUtil.encryptPassword(password,salt);
                adminUser.setPassword(passwd);
                adminUser.setSalt(salt);
                adminUser.setUpdateTime(DateUtil.getNowTimestamp());
                adminUserDao.save(adminUser);
            }

        }else {
            String salt="a123456";
            String passwd= PasswordUtil.encryptPassword(password,salt);
            userOld.setPassword(passwd);
            userOld.setSalt(salt);
            userOld.setUpdateTime(DateUtil.getNowTimestamp());
            userDao.save(userOld);
        }
        return res;
    }

    public JSONObject getUserCourseList(String mobile,int page,int size){
        JSONObject res = new JSONObject();
        List<UserCourseRes> userCourseResList=new ArrayList<>();
        List<UserCourse> userCourseList=new ArrayList<>();
        Map<String,User> mapUser=new HashMap<>();
        if("all".equals(mobile)){
            userCourseList=userCourseDao.findAll();
            List<String> userIds=new ArrayList<>();
            for(UserCourse userCourse:userCourseList){
                userIds.add(userCourse.getUserId());
            }
            List<User> userList=userDao.findByIdIn(userIds);
            for(User user:userList){
                mapUser.put(user.getId(),user);
            }
        }else {
            List<User> userList=userDao.findByMobileLike(mobile);
            List<String> userIds=new ArrayList<>();
            for(User user:userList){
                mapUser.put(user.getId(),user);
                userIds.add(user.getId());
            }
            userCourseList=userCourseDao.findByUserIdIn(userIds);
        }
        for(UserCourse userCourse:userCourseList){
            User user=mapUser.get(userCourse.getUserId());
            if(user==null){
                continue;
            }
            UserCourseRes userCourseRes=new UserCourseRes("createTime",2);
            userCourseRes.setId(userCourse.getId());
            userCourseRes.setUserId(userCourse.getUserId());
            userCourseRes.setExamType(userCourse.getExamType());
            userCourseRes.setCreateTime(userCourse.getCreateTime());
            userCourseRes.setUsername(user.getUsername());
            userCourseRes.setMobile(user.getMobile());
            userCourseResList.add(userCourseRes);
        }
        Collections.sort(userCourseResList);
        //实现分页
        int offset=(page-1)*size;
        int limit=page*size;
        int total=userCourseResList.size();
        if(limit>total){
            limit=total;
        }
        List<UserCourseRes>data=new ArrayList<>();
        if(total>0 && offset<limit) {
            data = userCourseResList.subList(offset, limit);
        }
        res.put("data",data);
        res.put("total",total);

        return res;
    }

    public JSONObject saveUserCourse(UserCourse userCourseReq,String userId){
        JSONObject res = new JSONObject();
        User user=userDao.findById(userCourseReq.getUserId());
        if(user==null){
            throw new WafException("", "用户不存在！", HttpStatus.NOT_ACCEPTABLE);
        }
        UserCourse userCourseOld=userCourseDao.findByExamTypeAndUserId(userCourseReq.getExamType(),userCourseReq.getUserId());

        if(userCourseOld!=null){
            throw new WafException("", "该用户已分配该课程，不能重复分配！", HttpStatus.NOT_ACCEPTABLE);
        }else {
            UserCourse userCourse = new UserCourse();
            userCourse.setId(UUID.randomUUID().toString().replace("-", ""));
            userCourse.setExamType(userCourseReq.getExamType());
            userCourse.setUserId(userCourseReq.getUserId());
            userCourse.setCreateTime(DateUtil.getNowTimestamp());
            userCourse.setUpdateTime(DateUtil.getNowTimestamp());
            userCourseDao.save(userCourse);
            UserTest userTestOld=userTestDao.findByExamTypeAndUserId(userCourseReq.getExamType(),userCourseReq.getUserId());
           if(userTestOld==null) {
               UserTest userTest = new UserTest();
               userTest.setId(UUID.randomUUID().toString().replace("-", ""));
               userTest.setExamType(userCourseReq.getExamType());
               userTest.setUserId(userCourseReq.getUserId());
               userTest.setCreateTime(DateUtil.getNowTimestamp());
               userTest.setUpdateTime(DateUtil.getNowTimestamp());
               userTestDao.save(userTest);
           }
        }
        return res;
    }


    public void deleteUserCourse(UserCourse userCourseReq) {
        JSONObject res = new JSONObject();
        UserCourse userCourseOld=userCourseDao.findByExamTypeAndUserId(userCourseReq.getExamType(),userCourseReq.getUserId());
        UserTest userTestOld=userTestDao.findByExamTypeAndUserId(userCourseReq.getExamType(),userCourseReq.getUserId());
        if(userCourseOld!=null){
            userCourseDao.delete(userCourseOld);
        }
        if(userTestOld!=null) {
            userTestDao.delete(userTestOld);
        }
    }
    public JSONObject getUserExamTypeInfo(String userId){
        JSONObject res = new JSONObject();
        UserExamType userExamType=userExamTypeDao.findByUserId(userId);
        if(userExamType==null){
            userExamType=new UserExamType();
        }
        res.put("examType",userExamType.getExamType());
        return res;
    }

    public JSONObject getMessageRelease(int type,int page,int size,String userId){
        JSONObject res = new JSONObject();
        Sort sort=new Sort(Sort.Direction.DESC,"updateTime");
        Pageable pageable = new PageRequest(page-1, size, sort);
        Page<MessageRelease> messageReleasePage=messageReleaseDao.findByType(type,pageable);
        List<MessageRelease> messageReleaseListOld=messageReleaseDao.findByType(type);
        List<MessageRelease> messageReleaseList=messageReleasePage.getContent();
        if(messageReleaseList.size()==0){
            messageReleaseList=new ArrayList<>();
        }
        res.put("data",messageReleaseList);
        res.put("total",messageReleaseListOld.size());
        return res;
    }

    public void delMessageRelease(String id){
        messageReleaseDao.delete(id);
    }


    public JSONObject saveUserExamType(UserExamType userExamTypeReq,String userId){
        JSONObject res = new JSONObject();
        UserExamType userExamTypeOld=userExamTypeDao.findByUserId(userId);
        if(userExamTypeOld==null){
            UserExamType userExamType=new UserExamType();
            userExamType.setId(UUID.randomUUID().toString().replace("-", ""));
            userExamType.setExamType(userExamTypeReq.getExamType());
            userExamType.setUserId(userId);
            userExamType.setCreateTime(DateUtil.getNowTimestamp());
            userExamType.setUpdateTime(DateUtil.getNowTimestamp());
            userExamTypeDao.save(userExamType);
        }else {
            userExamTypeOld.setExamType(userExamTypeReq.getExamType());
            userExamTypeOld.setUserId(userId);
            userExamTypeOld.setUpdateTime(DateUtil.getNowTimestamp());
            userExamTypeDao.save(userExamTypeOld);
        }
        return res;
    }


    public JSONObject saveMessageRelease(MessageRelease messageReleaseReq,String userId){
        JSONObject res = new JSONObject();
        MessageRelease messageReleaseOld=messageReleaseDao.findById(messageReleaseReq.getId());
        if(messageReleaseOld==null){
            MessageRelease messageRelease=new MessageRelease();
            messageRelease.setId(UUID.randomUUID().toString().replace("-", ""));
            messageRelease.setType(messageReleaseReq.getType());
            messageRelease.setTitle(messageReleaseReq.getTitle());
            messageRelease.setTitlePicUrl(messageReleaseReq.getTitlePicUrl());
            messageRelease.setDescribes(messageReleaseReq.getDescribes());
            messageRelease.setCreateTime(DateUtil.getNowTimestamp());
            messageRelease.setUpdateTime(DateUtil.getNowTimestamp());
            messageReleaseDao.save(messageRelease);
        }else {
            messageReleaseOld.setTitle(messageReleaseReq.getTitle());
            messageReleaseOld.setTitlePicUrl(messageReleaseReq.getTitlePicUrl());
            messageReleaseOld.setDescribes(messageReleaseReq.getDescribes());
            messageReleaseOld.setUpdateTime(DateUtil.getNowTimestamp());
            messageReleaseDao.save(messageReleaseOld);
        }
        return res;
    }

    public JSONObject getUserListXiaLa(String userName){
        JSONObject res = new JSONObject();
        List<User> userList=new ArrayList<>();
        if("all".equals(userName.trim())){
            userList=userDao.findAll();
        }else {
            userList=userDao.findByUsernameLike(userName);
        }
        if(userList.size()==0){
            userList=new ArrayList<>();
        }
        res.put("data",userList);
        return res;
    }
}
